class Solution
{
public:
    int totalFruit(vector<int> &fruits)
    {
        int maxFetch = 0;
        int curFetch = 1;
        int continuousSameType = 1;
        unordered_set<int> types;
        types.insert(fruits[0]);
        int n = fruits.size();
        for (int i = 1; i < n; ++i)
        {
            if (fruits[i] == fruits[i - 1])
            {
                ++continuousSameType;
                ++curFetch;
            }
            else if (types.count(fruits[i]))
            {
                continuousSameType = 1;
                ++curFetch;
            }
            else if (types.size() < 2)
            {
                types.insert(fruits[i]);
                continuousSameType = 1;
                ++curFetch;
            }
            else
            {
                maxFetch = max(maxFetch, curFetch);
                types.clear();
                types.insert(fruits[i - 1]);
                types.insert(fruits[i]);
                curFetch = continuousSameType + 1;
                continuousSameType = 1;
            }
        }
        maxFetch = max(maxFetch, curFetch);
        return maxFetch;
    }
};